/**
 * @param {number[][]} image
 * @param {number} sr
 * @param {number} sc
 * @param {number} newColor
 * @return {number[][]}
 */
export var floodFill = function (image, sr, sc, newColor) {
  const oldColor = image[sr][sc]
  if (oldColor === newColor) return image
  return findNearAndFill(image, sr, sc, newColor, oldColor)
}

function findNearAndFill(image, sr, sc, newColor, oldColor) {
  if (sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length) return image
  if (image[sr][sc] !== oldColor) return image
  image[sr][sc] = newColor
  // filled.push(`${sr},${sc}`)
  const nears = [
    [sr - 1, sc],
    [sr, sc + 1],
    [sr + 1, sc],
    [sr, sc - 1],
  ]
  for (let i = 0; i < nears.length; i++) {
    findNearAndFill(image, nears[i][0], nears[i][1], newColor, oldColor)
  }
  return image
}
